package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXB;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.costants.CustomersConstants;
import com.topisv.tms.entity.CusStockMerge;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.exception.QMErrorCode;
import com.topisv.tms.repository.CustomersDao;
import com.topisv.tms.rest.qimen.qmentity.request.InventoryQuery.Criteria;
import com.topisv.tms.rest.qimen.qmentity.request.InventoryQuery.CriteriaList;
import com.topisv.tms.rest.qimen.qmentity.response.ResponseFlagType;
import com.topisv.tms.rest.qimen.qmentity.response.InventoryQuery.ExtendProps;
import com.topisv.tms.rest.qimen.qmentity.response.InventoryQuery.InventoryQuery;
import com.topisv.tms.rest.qimen.qmentity.response.InventoryQuery.Item;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.rest.qimen.response.ResponseParams;
import com.topisv.tms.rest.qimen.util.validator.ValidatorUtil;
import com.topisv.tms.service.CusStockMergeService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.stock.CusStockService;

/**
 * 库存查询接口服务类
 * ERP可以通过奇门接口实时查询wms库存信息
 * @author chenhongtao
 * @version [v0.0.6, 2016年5月13日]
 * @see         [相关类/方法]（可选）
 * @since      [产品/模块版本] （必须）
 */
@Component
@Transactional(readOnly=true)
public class InventoryQueryService {
	
	private static final Logger logger = LoggerFactory.getLogger(StockoutCreateService.class);
	@Autowired
	private CusStockService cusStockService ; 
	
	@Autowired
	private CusStockMergeService cusStockMergeService ; 	
	
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService ;
	
	@Autowired
	private CustomersDao customersDao;
	
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public ResponseParams execute(RequestParams params) throws PaiUException {
		
		String xmlString = params.getRequestXml();
		InventoryQuery inventoryQuery = new InventoryQuery();
		List<Item> items = new ArrayList<Item>(); ;
		try {
			logger.info("库存查询"+xmlString);
			String stringXml = params.getRequestXml();
			//解析xml
			CriteriaList criteriaList = JAXB.unmarshal(new StringReader(stringXml), CriteriaList.class);
			
            // 报文校验
            String reqValidatorMsg = ValidatorUtil.qmXmlValidator(criteriaList);
            if (!ValidatorUtil.SUCCESS_CODE.equals(reqValidatorMsg)) {
                ResponseParams response = new ResponseParams();
                response.setResponseXml(reqValidatorMsg.toString());
                return response;
            }
			
			List<Criteria> criterias = criteriaList.getCriteria() ;
			if(null != criterias && !criterias.isEmpty()){
				String warehouseCode = "";
				String customerCode ="";
				String sku = "";
				ExtendProps extendProps = new ExtendProps();
				for(Criteria criteria:criterias){
					//合并库存
					warehouseCode = criteria.getWarehouseCode() ; 
					//customerCode = criteria.getOwnerCode() ;
					//根据itemid获取sku
					if(StringUtils.isBlank(criteria.getItemId())){
						continue;
					}
					EdiGoodsSku ediGoodsSku = ediGoodsSkuService.loadById(Long.parseLong(criteria.getItemId())) ;
					if(null == ediGoodsSku){
						continue;
					}
					customerCode=ediGoodsSku.getCustomerCode() ; 
					sku = ediGoodsSku.getSku() ;
					int quantity = 0;
					int lockQuantity = 0 ;
					List<CusStock> cusStocks = null; 
					List<CusStockMerge> cusStockMerges = null ;
					Customers customer = customersDao.findByCustomerCode(customerCode);
					if (CustomersConstants.ALL_WAREHOUSE_STOCK.equals(customer.getStockQueryType())) { // 根据商家库存查询状态决定方式
					    cusStocks = cusStockService.loadStock(customerCode,sku) ; 
                        cusStockMerges = cusStockMergeService.findCustomerWarSku(customerCode, sku) ;
                    } else if (StringUtils.isNotBlank(warehouseCode)) {
                        cusStocks = cusStockService.loadStock(warehouseCode,customerCode,sku) ; 
                        cusStockMerges = cusStockMergeService.findCustomerWarSku2(customerCode, warehouseCode, sku) ;
                    } else {
						cusStocks = cusStockService.loadStock(customerCode,sku) ; 
						cusStockMerges = cusStockMergeService.findCustomerWarSku(customerCode, sku) ;
					}
					Item item = new Item();
					item.setWarehouseCode(warehouseCode);
					item.setItemCode(criteria.getItemCode());
					item.setInventoryType("ZP");
					item.setBatchCode("");
					item.setProductDate("");
					item.setExpireDate("");
					item.setProduceCode("");
					item.setExtendProps(extendProps);
					for(CusStock cusStock:cusStocks){
						quantity += cusStock.getSalesNum();
						lockQuantity += cusStock.getUnusedNum()+cusStock.getOrderNum()+cusStock.getLockedNum()+cusStock.getTransportNum()+cusStock.getAirNum() ;
					}
					for(CusStockMerge cusStockMerge:cusStockMerges){
						quantity -= cusStockMerge.getOrderNum();
						lockQuantity += cusStockMerge.getOrderNum();
					}
					item.setQuantity(String.valueOf(quantity));
					item.setLockQuantity(String.valueOf(lockQuantity));
					items.add(item);
				}
				logger.info("入库查询成功,methed=inventory.query");
				inventoryQuery.setFlag(ResponseFlagType.SUCCESS.getType());
				inventoryQuery.setCode(QMErrorCode.SUCCESS.getCode());
				inventoryQuery.setMessage(QMErrorCode.SUCCESS.getMessage());
				inventoryQuery.setItem(items);
			}else{
				logger.info("解析报文为空:"+stringXml);
				inventoryQuery.setFlag(ResponseFlagType.FAILURE.getType());
				inventoryQuery.setCode(QMErrorCode.SYS_ERROR.getCode());
				inventoryQuery.setMessage("解析报文为空");
				inventoryQuery.setItem(items);
			}
		}catch (Exception e) {
			logger.info("库存查询错误",e);
			inventoryQuery.setFlag(ResponseFlagType.FAILURE.getType());
			inventoryQuery.setCode(QMErrorCode.SYS_ERROR.getCode());
			inventoryQuery.setMessage("库存查询失败");
			inventoryQuery.setItem(items);
			return getResponse(inventoryQuery);
		}
		return getResponse(inventoryQuery);
	}
	
	public ResponseParams getResponse(InventoryQuery inventoryQuery){
		ResponseParams response = new ResponseParams();
		StringWriter writer = new StringWriter();
		JAXB.marshal(inventoryQuery,writer);
		response.setResponseXml(writer.toString());
		return response;
	}
}
